package com.ylx.excel.excel.handler;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ylx.excel.config.SyncExcelThreadLocal;
import com.ylx.excel.excel.model.SyncExcelData;
import com.ylx.excel.model.ExcelData;
import com.ylx.excel.service.ExcelDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Description: <br/>
 * date: 2022/9/2 11:30<br/>
 * 多线程异步监听器
 *
 * @author yanglixin2<br />
 */
@Slf4j
@Component
public class SyncListener extends AnalysisEventListener<SyncExcelData> {

    private static final int MAX_NUM = 10000;

    @Autowired
    private ExcelDataService excelDataService;

    /**
     * 读取数据
     */
    @Override
    public void invoke(SyncExcelData excelData, AnalysisContext context) {
        Integer line = context.readRowHolder().getRowIndex() + 1;
        Integer sheetNo = context.readSheetHolder().getSheetNo();
        String sheetName = context.readSheetHolder().getSheetName();
        List<SyncExcelData> dataList = SyncExcelThreadLocal.getData();
        excelData.setLine(line);
        excelData.setSheetName(sheetName);
        excelData.setSheetNo(sheetNo);
        dataList.add(excelData);
        if (dataList.size() >= MAX_NUM) {
            //超过最大限制,保存数据并且清空集合
            saveData(dataList);
            dataList.clear();
        }
    }

    /**
     * 读取数据完毕
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("一个Sheet数据读取完毕!");
        List<SyncExcelData> syncExcelData = SyncExcelThreadLocal.getData();
        if (CollUtil.isEmpty(syncExcelData)) {
            log.info("当前Sheet为空");
        }
        log.info("当前Sheet数据条数为: {}", syncExcelData.size());
        saveData(syncExcelData);
        log.info("==========>一个Sheet导入完毕<===============");
        SyncExcelThreadLocal.remove();
    }

    private void saveData(List<SyncExcelData> dataList) {
        List<ExcelData> excelDataList = dataList.stream()
                .map(data -> BeanUtil.copyProperties(data, ExcelData.class))
                .collect(Collectors.toList());
        excelDataService.saveBatch(excelDataList);
    }
}
